package com.answer.service.impl;

import com.answer.lucenu.QuestionIndex;
import com.answer.model.Question;
import com.answer.service.QuestionService;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import java.io.File;
import java.util.HashMap;
import java.util.List;

/**
 * Created by Administrator on 2017/4/28.
 */
@Component
public class InitQuesIndex implements ServletContextListener, ApplicationContextAware {

    private static ApplicationContext applicationContext;
    //问题索引
    private QuestionIndex questionIndex = new QuestionIndex();

    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }

    public void contextInitialized(ServletContextEvent servletContextEvent) {
        ServletContext application = servletContextEvent.getServletContext();
        String path = "C://luceneq";
        File file = new File(path);
        if (!file.exists()) {
            if (file.mkdir()) {
                QuestionService questionService = (QuestionService) applicationContext.getBean("questionService");
                List<Question> questions = questionService.listByPage(new HashMap<String, Object>());
                for (Question ques : questions) {
                    try {
                        questionIndex.addIndex(ques);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }

    public void contextDestroyed(ServletContextEvent servletContextEvent) {

    }
}
